<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="购买方式:">
        <el-select
          v-model="meansOfPurchaseQ"
          clearable
          filterable
          default-first-option
          placeholder="请选择"
        >
          <el-option
            v-for="item in purchasePatternList"
            :key="item.encoding"
            :label="item.name"
            :value="item.encoding"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消费类型:">
        <el-select
          v-model="consumptionTypeQ"
          clearable
          filterable
          default-first-option
          placeholder="请选择"
        >
          <el-option
            v-for="item in consumeTypeList"
            :key="item.encoding"
            :label="item.name"
            :value="item.encoding"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支出用于:">
        <el-select
          v-model="disbursementUseOnQ"
          clearable
          filterable
          default-first-option
          placeholder="请选择"
        >
          <el-option
            v-for="item in expenditurePurposeList"
            :key="item.encoding"
            :label="item.name"
            :value="item.encoding"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select
          v-model="modeOfPaymentQ"
          clearable
          filterable
          default-first-option
          placeholder="请选择"
        >
          <el-option
            v-for="item in payPatternList"
            :key="item.encoding"
            :label="item.name"
            :value="item.encoding"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地点">
          <el-cascader
            v-model="areaQ"
            :options="areOptions"
            clearable
            filterable
            default-first-option
            style="width: 220px"
          ></el-cascader>
        </el-form-item>
        </el-form>
        <el-form :inline="true" class="demo-form-inline">
      <el-form-item class="switch">
        <el-switch
          style="display: block"
          v-model="dataQueryFalg"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="时间范围："
          inactive-text="时间节点"
          @change="
            () => {
              if (dataQueryFalg) {
                Form.dateStr = [];
                year = '';
                month = '';
                dates = [];
              } else Form.dates = [];
            }
          "
        >
        </el-switch>
      </el-form-item>
      <el-form-item v-if="dataQueryFalg">
        <el-date-picker
          v-model="Form.dates"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="!dataQueryFalg">
        <div class="block">
          <span class="demonstration">年</span>
          <el-date-picker
            v-model="year"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
            @change="clearOtherDate('year')"
          >
          </el-date-picker>
          <span class="demonstration">月</span>
          <el-date-picker
            v-model="month"
            type="month"
            placeholder="选择月"
            value-format="yyyyMM"
            @change="clearOtherDate('month')"
          >
          </el-date-picker>
          <span class="demonstration">多个日期</span>
          <el-date-picker
            type="dates"
            v-model="dates"
            placeholder="选择一个或多个日期"
            value-format="yyyyMMdd"
            @change="clearOtherDate('dates')"
          >
          </el-date-picker>
        </div>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="searchData()"
        v-if="hasPerm('disburse.list')">查询</el-button
      >
      <el-button
        type="default"
        @click="
          () => {
            year = '';
            month = '';
            dates = [];
            meansOfPurchaseQ = '';
            consumptionTypeQ = '';
            disbursementUseOnQ = '';
            modeOfPaymentQ = '';
            areaQ = [];
            Form.dates = [];
            Form.dateStr = [];
          }
        "
        >清空</el-button
      >
    </el-form>

    <el-button
      type="success"
      size="small"
      style="margin-bottom: 10px"
      icon="el-icon-document-add"
      @click="create()"
      v-if="hasPerm('disburse.add')">新增</el-button
    >
    <span>总计：{{moneySum}}</span>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      stripe
      highlight-current-row
      :key="tableKey"
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        label="购买方式"
        prop="meansOfPurchase"
        width="100"
        align="center"
        :formatter="formatter1"
      />
      <el-table-column
        label="消费类型"
        prop="consumptionType"
        width="100"
        align="center"
        :formatter="formatter2"
      />
      <el-table-column
        label="支出用于"
        prop="disbursementUseOn"
        width="100"
        align="center"
        :formatter="formatter3"
      />
      <el-table-column prop="detail" label="支出明细" align="center" />
      <el-table-column
        label="支付方式"
        prop="modeOfPayment"
        width="100"
        align="center"
        :formatter="formatter4"
      />
      <el-table-column
        prop="paymentAmount"
        label="支付金额"
        width="100"
        align="center"
      />
      <el-table-column
        prop="payDate"
        label="支付日期"
        width="100"
        align="center"
      />
      <el-table-column
        prop="acquireDate"
        label="获得日期"
        width="100"
        align="center"
      />
      <el-table-column
        prop="depleteDate"
        label="耗尽日期"
        width="100"
        align="center"
      />
      <el-table-column
        prop="area"
        label="地点"
        width="120"
        align="center"
        :formatter="formatterArea"
      />

      <el-table-column label="操作" width="200" align="center" v-if="hasPerm('disburse.update')|hasPerm('disburse.delete')">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="update(scope.row)"
            v-if="hasPerm('disburse.update')">修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)"
            v-if="hasPerm('disburse.delete')">删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 拟态框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      :close="
        () => {
          this.$nextTick.Form.clearValidate();
        }
      "
    >
      <el-form
        ref="Form"
        :model="Form"
        :rules="menuValidateRules"
        label-width="120px"
        :inline="true"
      >
        <el-form-item label="购买方式" prop="meansOfPurchase">
          <el-select
            v-model="Form.meansOfPurchase"
            clearable
            filterable
            default-first-option
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in purchasePatternList"
              :key="item.encoding"
              :label="item.name"
              :value="item.encoding"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消费类型" prop="consumptionType">
          <el-select
            v-model="Form.consumptionType"
            clearable
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in consumeTypeList"
              :key="item.encoding"
              :label="item.name"
              :value="item.encoding"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支出用于" prop="disbursementUseOn">
          <el-select
            v-model="Form.disbursementUseOn"
            clearable
            filterable
            default-first-option
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in expenditurePurposeList"
              :key="item.encoding"
              :label="item.name"
              :value="item.encoding"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支出明细" prop="detail">
          <el-input v-model="Form.detail" style="width: 220px" />
        </el-form-item>
        <el-form-item label="支付方式" prop="modeOfPayment">
          <el-select
            v-model="Form.modeOfPayment"
            clearable
            filterable
            default-first-option
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in payPatternList"
              :key="item.encoding"
              :label="item.name"
              :value="item.encoding"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input v-model="Form.paymentAmount" style="width: 220px" />
        </el-form-item>
        <el-form-item label="支付日期" prop="payDate">
          <el-date-picker
            v-model="Form.payDate"
            type="datetime"
            placeholder="选择支付日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="获得日期" prop="acquireDate">
          <el-date-picker
            v-model="Form.acquireDate"
            type="datetime"
            placeholder="选择获得日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="耗尽日期" prop="depleteDate">
          <el-date-picker
            v-model="Form.depleteDate"
            type="datetime"
            placeholder="选择耗尽日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地点" prop="area">
          <el-cascader
            v-model="Form.area"
            :options="areOptions"
            clearable
            filterable
            default-first-option
            style="width: 220px"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="是否计入">
          <el-switch v-model="Form.isIncluded"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button type="primary" @click="append()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="initTableList"
    />
  </div>
</template>
<script>
import disburseList from "@/api/account/disburseList";
import codeLibraryList from "@/api/account/codeLibraryList";
import { getToken } from "@/utils/auth";
import { getInfo } from "@/api/login";

const dateForm = {
  userId: "",
  meansOfPurchase: "",
  consumptionType: "",
  disbursementUseOn: "",
  detail: "",
  modeOfPayment: "",
  paymentAmount: "",
  payDate: "",
  acquireDate: "",
  depleteDate: "",
  area: "",
  isIncluded: "",
};

export default {
  // data:{
  // },
  data() {
    //定义变量和初始值
    return {
      listLoading: true, // 数据是否正在加载
      list: null, //查询之后接口返回集合
      page: 1, //当前页
      limit: 8, //每页记录数
      total: 0, //总记录数
      queryForm: {}, //查询条件form中的数据
      dialogFormVisible: false,
      Form: { ...dateForm },
      dataQueryFalg: true,
      userId: 0,
      tableKey: 0,
      purchasePatternList: {}, //用于list的码值转换
      purchasePatternMap: {},
      meansOfPurchaseQ: "", //查询用
      consumeTypeList: {},
      consumeTypeMap: {},
      consumptionTypeQ: "",
      expenditurePurposeList: {},
      expenditurePurposeMap: {},
      disbursementUseOnQ:"",
      payPatternList: {},
      payPatternMap: {},
      modeOfPaymentQ:"",
      areaQ:[],
      areaCode: "",
      areOptions: [],
      year: "",
      month: "",
      dates: [],
      moneySum: 0,
      menuValidateRules: {
        //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
        meansOfPurchase: [
          { required: true, trigger: "blur", message: "请选择购买方式" },
        ],
        consumptionType: [
          { required: true, trigger: "blur", message: "请选择消费类型" },
        ],
        disbursementUseOn: [
          { required: true, trigger: "blur", message: "请选择支出用于" },
        ],
        modeOfPayment: [
          { required: true, trigger: "blur", message: "请选择支付方式" },
        ],
        payDate: [
          { required: true, trigger: "blur", message: "请选择支付日期" },
        ],
        paymentAmount: [
          { required: true, trigger: "blur", message: "金额必须输入" },
          {
            validator: (rule, value, callback) => {
              if (
                /(^[1-9]([0-9]{0,5})(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(
                  value
                ) == false
              ) {
                callback(new Error("请输入正确的金额"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      dialogFormValue: "新增",
    };
  },
  created() {
    //在页面渲染之前执行，一般调用methods定义的方法
    disburseList.getArea().then((res) => {
      this.areOptions = res.data.list;
    });
    getInfo(getToken()).then((res) => {
      this.userId = res.data.userId;
      Promise.all([this.getCode()]).then((res) => {
        this.listLoading = false;
        this.initTableList();
      });
    });
  },
  methods: {
    //码值列表的方法
    initTableList(page = 1) {
      console.log("被调用");
      this.page = page;
      this.tableKey = Math.random();
      this.Form.meansOfPurchase = this.meansOfPurchaseQ;
      this.Form.consumptionType = this.consumptionTypeQ;
      this.Form.disbursementUseOn = this.disbursementUseOnQ;
      this.Form.modeOfPayment = this.modeOfPaymentQ;
      this.Form.area = this.areaQ[2];
      
      console.log("this.userId", this.userId);
      this.Form.userId = this.userId;
      disburseList.findAll(this.page, this.limit, this.Form).then((res) => {
        this.list = res.data.rows;
        this.total = res.data.total;
        console.log("res", res);
      });
      disburseList.getMoneySum(this.Form).then((res)=>{
        this.moneySum = res.data.moneySum;
      })
    },
    create() {
      this.dialogFormVisible = true;
      this.Form = { ...dateForm };
      //等弹窗里的form表单的dom渲染完在执行this.$refs.Form.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.Form) {
          this.$refs.Form.clearValidate();
        }
      });
    },
    restData() {
      this.dialogFormVisible = false;
      //清除查询条件
      //this.Form = { ...dateForm };
    },

    append() {
      this.$refs.Form.validate((valid) => {
        if (valid) {
          if (!this.Form.gmtCreate) {
            this.Form.userId = this.userId;
            // 只传叶子节点
            this.Form.area = this.Form.area[2];
            disburseList.saveDisburse(this.Form).then((res) => {
              this.$message({
                type: "success",
                message: "添加数据成功!",
              });
              this.restData();
              this.initTableList();
            });
          } else {
            if (this.Form.area instanceof Array)
              this.Form.area = this.Form.area[2];
            disburseList.updateById(this.Form).then((res) => {
              this.$message({
                type: "success",
                message: "更新数据成功!",
              });
              this.restData();
              this.initTableList();
            });
          }
        }
      });
    },
    removeById(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          disburseList.removeById(id).then((res) => {
            this.$message({
              type: "success",
              message: "删除数据成功!",
            });
            this.restData();
            this.initTableList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    update(row) {
      //等弹窗里的form表单的dom渲染完在执行this.$refs.Form.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.Form) {
          this.$refs.Form.clearValidate();
        }
      });
      this.dialogFormVisible = true;
      this.Form = { ...row };
    },
    searchData() {
      this.initTableList();
    },
    formatter1(row, column, cellValue) {
      return this.purchasePatternMap[cellValue];
    },
    formatter2(row, column, cellValue) {
      return this.consumeTypeMap[cellValue];
    },
    formatter3(row, column, cellValue) {
      return this.expenditurePurposeMap[cellValue];
    },
    formatter4(row, column, cellValue) {
      return this.payPatternMap[cellValue];
    },
    formatterArea(row, column, cellValue) {
      let listAreaName = "";
      if (cellValue) {
        this.areOptions.forEach((item1) => {
          if (item1.value === cellValue.substring(0, 2) + "0000") {
            listAreaName += item1.label + "/";
            item1.children.forEach((item2) => {
              if (item2.value === cellValue.substring(0, 4) + "00") {
                if (listAreaName != item2.label + "/") {
                  listAreaName += item2.label + "/";
                }
                item2.children.forEach((item3) => {
                  if (item3.value === cellValue) {
                    listAreaName += item3.label;
                  }
                });
              }
            });
          }
        });
      }
      return listAreaName;
    },
    getCode() {
      codeLibraryList.findAllByCode("purchasePattern").then((res) => {
        this.purchasePatternList = res.data.rows;
        this.purchasePatternList.forEach((item) => {
          this.purchasePatternMap[item.encoding] = item.name;
        });
        if (this.list) {
          this.list = this.list.slice(0);
        }
      });
      codeLibraryList.findAllByCode("consumeType").then((res) => {
        this.consumeTypeList = res.data.rows;
        this.consumeTypeList.forEach((item) => {
          this.consumeTypeMap[item.encoding] = item.name;
        });
        if (this.list) {
          this.list = this.list.slice(0);
        }
      });
      codeLibraryList.findAllByCode("expenditurePurpose").then((res) => {
        this.expenditurePurposeList = res.data.rows;
        this.expenditurePurposeList.forEach((item) => {
          this.expenditurePurposeMap[item.encoding] = item.name;
        });
        if (this.list) {
          this.list = this.list.slice(0);
        }
      });
      codeLibraryList.findAllByCode("payPattern").then((res) => {
        this.payPatternList = res.data.rows;
        this.payPatternList.forEach((item) => {
          this.payPatternMap[item.encoding] = item.name;
        });
        if (this.list) {
          this.list = this.list.slice(0);
        }
      });
    },

    clearOtherDate(arg) {
      if (arg === "year") {
        this.month = "";
        this.dates = [];
        console.log("year", this.year);
        this.Form.dateStr = [];
        this.Form.dateStr.push(this.year);
      } else if (arg === "month") {
        this.year = "";
        this.dates = [];
        console.log("month", this.month);
        this.Form.dateStr = [];
        this.Form.dateStr.push(this.month);
      } else if (arg === "dates") {
        this.month = "";
        this.year = "";
        console.log("dates", this.dates);
        this.Form.dateStr = [];
        this.Form.dateStr = this.dates;
      }
    },
  },
};
</script>
<style scoped>
.el-form-item.switch /deep/ .el-form-item__content {
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
}
</style>
<style>
.el-switch__label--right {
  font-weight: 700;
}
.el-switch__label--left {
  font-weight: 700;
}
</style>
